#pragma once

#include "../../server/net/Buffer.h"
#include <google/protobuf/io/zero_copy_stream.h> //零拷贝
namespace yhaida
{
    class BufferOutputStream : public google::protobuf::io::ZeroCopyOutputStream // https://izualzhy.cn/protobuf-zerocopy
    {
    public:
        BufferOutputStream(Buffer *buff)
            : _buffer(CHECK_NOTNULL(buff)),
              _originalSize(buff->readableBytes())
        {
        }
        //重写ZeroCopyOutputStream的虚函数
    public:
        virtual bool Next(void **data, int *size) override
        {
            _buffer->ensureWritableBytes(4096);//4M
            *data = _buffer->beginWrite();
            *size = static_cast<int>(_buffer->writableBytes());
            _buffer->hasWritten(*size);
            return true;
        }

        virtual void BackUp(int count)override
        {
            _buffer->unwrite(count);
        }
        virtual int64_t ByteCount() const override
        {
            return _buffer->readableBytes() - _originalSize;
        }

    private:
        Buffer *_buffer;
        size_t _originalSize;
    };

}
